<script setup>

import router from "../../../router/index.js";
import {onMounted, ref} from "vue";
import {getResponseData} from "../../../request/index.js";
import {updateByEmpIdApi} from "../../../api/role.js";
import {ElMessage} from "element-plus";
import {listApi} from "../../../api/axios.js";
import {listByEmpIdApi} from "../../../api/role.js";
import MyNav from "../../../components/MyNav.vue";

// 获取路由中的员工主键
let empId = router.currentRoute.value.query['empId'];

// 路径导航
const navItems = [
  {icon: 'Avatar', label: '用户管理'},
  {icon: 'User', label: '员工列表', url: '/Emp'},
  {icon: 'Edit', label: '重设角色'},
];
// 全部角色 + 角色主键数组
let allRoles = ref([]);
let roleIds = ref([]);

/* ======================================== 确认修改角色 ================================================ */
async function updateRoles() {
  let data = getResponseData(await updateByEmpIdApi(empId, roleIds.value));
  if (data) {
    ElMessage.success('角色重设成功，下次登录生效！');
  }
}

/* ======================================== 加载函数 ================================================ */

onMounted(async () => {
  // 查询全部角色
  Object.values(getResponseData(await listApi({module: 'role'}))).forEach(role => {
    allRoles.value.push({label: role['title'], key: role['id']});
  });

  // 查询该员工的角色
  Object.values(getResponseData(await listByEmpIdApi(empId))).forEach(role => {
    roleIds.value.push(role['id']);
  });
});
</script>

<template>
  <div class="emp-roles-body">
    <my-nav :items="navItems"/>
    <el-transfer class="emp-roles-transfer"
                 filterable filter-placeholder="输入关键字"
                 v-if="allRoles.length > 0"
                 v-model="roleIds"
                 :data="allRoles"
                 :titles="['全部可选项', '当前已选项']"
                 :props="{key: 'key', label: 'label'}"
                 :button-texts="['移除', '添加']"/>
    <el-button class="update-roles-btn" type="primary" @click="updateRoles">确认修改</el-button>
  </div>
</template>

<style scoped lang="scss">
.emp-roles-body {
  text-align: center; // 内容居中

  .emp-roles-transfer{
    margin-top: 65px; // 上外边距
  }

  .update-roles-btn {
    margin-top: 20px; // 上外边距
    width: 53%; // 宽度
  }
}

/* 修改EL穿梭框高度 */
:deep(.el-transfer-panel), :deep(.el-transfer-panel__body) {
  height: 500px; // 高度
}
</style>